//'use strict'

var fs = require("fs");
var os = require('os');
var path = require('path');

var arguments = process.argv.splice(2);


if (arguments.length < 2) {
    console.log('[error] Program requires two parameters(Absolute path)');
    console.log('[info:] like this:node app.js srcDir desDir');
    return;
}

var srcPath = getAbsolutePath(arguments[0]);
var desPath = getAbsolutePath(arguments[1]);

// var srcPath = path.join(__dirname, '1');
// var desPath = path.join(__dirname, 'test');


getFileList(srcPath);



function getFileList(fullPath) {
    fs.readdir(fullPath, function (err, files) {
        files.forEach(function (fileName, iCount) {
            fs.stat(path.join(fullPath, fileName), function (err, stats) {
                if (err) {
                    console.log('[error] ', err);
                    return;
                }

                if (stats.isFile()) {
                    var relativePath = path.relative(srcPath, fullPath);
                    var replace = { win32: '..\\', linux: '../' };

                    var srcFile = path.normalize(fullPath + '/' + fileName);
                    var desFile = path.normalize(path.join(desPath,
                        relativePath.replace(replace[os.platform])) + '/' + fileName);

                    //console.log('src file:', srcFile);
                    //console.log(path.join('des file:', desFile));

                    copyFile(desFile, srcFile);

                } else if (stats.isDirectory()) {
                    //console.log('dir');
                    getFileList(path.join(fullPath, fileName));
                }
            });
        });
    });
}

/**
 * 
 * @param {*String} filepath 拷贝后的目标文件绝对路径
 * @param {*string} src -需要拷贝的文件绝对路径
 */
function copyFile(filepath, src) {
    var pathInfo = path.parse(filepath);
    var searchvalue = pathInfo.root[pathInfo.root.length - 1]
    var start = 0;
    var found = pathInfo.dir.indexOf(searchvalue);
    var subPath = '';
    var dirs = [];

    if (found != -1) {
        while (true) {
            subPath = pathInfo.dir.substr(start, found - start + 1);
            if (subPath != '') {
                dirs.push(subPath);
            }
            start = found + 1;
            found = pathInfo.dir.indexOf(searchvalue, start);
            if (found == -1) {
                if (start < pathInfo.dir.length) {
                    dirs.push(pathInfo.dir.substr(start));
                }
                break;
            }
        }
    }

    subPath = '';
    dirs.forEach(function (dir, num) {
        subPath += dir;

        var copy = function () {
            if (num == dirs.length - 1 && pathInfo.base != '') {
                var read = fs.createReadStream(src);
                var write = fs.createWriteStream(filepath);
                read.pipe(write);
                console.log('[info] create file:', filepath);
            }
        };

        if (!fs.existsSync(subPath)) {
            fs.mkdir(subPath, function (err) {
                if (err) {
                    console('[error] ', err);
                    return;
                }

                console('[info] create dir:', subPath);
                copy();

            });
        } else {
            copy();
        }

    });

}

//获取文件的后后缀名
function getSuffix(url) {
    var lastIndex = url.lastIndexOf('.');
    if (lastIndex == -1) {
        console.log('[error] path do not inclue a file name:', url);
        return;
    }

    return url.substring(lastIndex);
}

//获取绝对路径
function getAbsolutePath(url) {
    if (!path.isAbsolute(url)) {
        url = path.join(__dirname, url);
    }
    return url
}